<?php
if ( is_admin() ) {
	add_action("admin_print_styles", 'add_css_for_meta_box');
	wp_deregister_script('jquery');
	add_action("admin_print_scripts", 'add_script_for_meta_box');
	
	add_action("admin_init", 'meta_tourInfo');
	add_action('admin_menu' , 'remove_duration_taxonomies');
	
	/* Do something with the data entered */
	add_action("save_post", 'myplugin_save_postdata');	
	
	add_action('delete_post', 'delete_postdata_when_remove_in_trash', 10);
	
	/*
	add_action('restrict_manage_posts', 'my_restrict_manage_posts');
	add_filter('manage_edit-tour_sortable_columns', 'tour_sortable_columns');
	add_filter('manage_edit-tour_columns', 'add_new_tour_columns');
	add_action('manage_tour_posts_custom_column', 'tour_columns_display');
	add_filter('parse_query','filter_cat_tour');
	
	add_action("admin_print_styles-edit.php", 'add_css_script_top_column'); // hoặc admin_head-{$hook}, vd: admin_head-edit.php
	add_filter('manage_edit-tour_sortable_columns', 'top_sortable_columns');
	add_filter('request', 'top_column_orderby');
	add_filter('manage_edit-tour_columns', 'add_code_columns');
	add_filter('manage_edit-tour_columns', 'add_top_columns');
	add_action('manage_tour_posts_custom_column', 'top_columns_display');
	
	add_action('quick_edit_custom_box',  'add_quick_edit_codeTour', 10, 2);
	add_action('save_post', 'save_quick_edit_codeTour');
	add_action('admin_footer', 'quick_edit_javascript_codeTour');
	add_filter('post_row_actions', 'expand_quick_edit_codeTour', 10, 2);
	/*
	$fileName = basename($_SERVER['SCRIPT_FILENAME']);
	if ( $fileName == 'post-new.php' || ( $fileName == 'post.php' && $_GET['action'] == 'edit' ) ) {
		add_action("admin_print_styles", 'add_css_for_priceInfo');
		add_action("wp_print_scripts", 'add_script_for_priceInfo');
	}*/
	//add_action('save_post', 'save_details');
}

add_action('init', 'create_post_taxonomies');
function create_post_taxonomies() {
	register_taxonomy('tour_duration', 'post', array(
		'hierarchical'	=> false, 
		'label'			=> 'Tour Durations', 
		'show_ui' 		=> true,
		'query_var'		=> true, 
		'rewrite'		=> array('slug' => 'tour-duration', 'with_front' => false)
	));
}
function remove_duration_taxonomies() {
	remove_meta_box('tagsdiv-tour_duration','post','side');
}
function meta_tourInfo(){
	add_meta_box("tourInfo", "Nội dung tóm tắt", "tour_custom_box", 'post', "normal", "low");
	//add_meta_box("tabTour", "Thêm tab tour", "tabTour", 'post', "normal", "low");
	add_meta_box("tourAttr", "Các thuộc tính Tour", "sidebar_custom_post_type", 'post', "side", "low");
}
function sidebar_custom_post_type() 
{
	global $post;
	$postID		= $post->ID;
	$custom		= get_post_meta( $postID, '_cpt_tour_attr', true );
	$topNews	= get_post_meta( $postID, '_cpt_top_tour', true );
	$tripCode	= $custom["_trip_code"];
	$priceFrom	= $custom['_price_from'];
	$priceTo	= $custom['_price_to'];
	$map_title	= $custom['_map_title'];
	$map_source	= $custom['_map_source'];
	wp_nonce_field( plugin_basename( __FILE__ ), 'cpt_noncename' );
	
	// Get all theme taxonomy terms
	// $taxterms = get_terms( $tax, 'orderby=count&offset=1&hide_empty=0&fields=all' );
	$durations = get_terms('tour_duration', 'hide_empty=0'); 
	?>
    
	<table width="100%">
    	<tr><td>Trip code</td>
        	<td><input type="text" name="trip_code" value="<?php echo $tripCode; ?>" style="width:62px" /></td>
        </tr>
        <tr><td>Duration</td>
        	<td><select name='duration_option' id='duration_option'>
					<?php $names = wp_get_object_terms($post->ID, 'tour_duration'); ?>
                    <option value='' <?php if (!count($names)) echo "selected";?>>None</option>
                    <?php
                    foreach ($durations as $duration) {
                        if (!is_wp_error($names) && !empty($names) && !strcmp($duration->slug, $names[0]->slug)) 
                            echo "<option value='" . $duration->slug . "' selected>" . $duration->name . "</option>\n"; 
                        else
                            echo "<option value='" . $duration->slug . "'>" . $duration->name . "</option>\n"; 
                    } ?>
                </select>
			</td>
        </tr>
        <tr><td>Price</td>
        	<td><input type="text" name="price_from" value="<?php echo $priceFrom; ?>" style="width:62px" /> - <input type="text" name="price_to" value="<?php echo $priceTo; ?>" style="width:62px" /> $</td>
        </tr>
        <tr><td>Top tour</td>
        	<td><input type="checkbox" name="top_tour"<?php if( $topNews ): echo ' checked="checked"'; endif; ?> /></td>
        </tr>
        <tr><td colspan="2" style="padding-top:8px;">Interactive map [Name] - [Source]</td></tr>
        <tr><td>Name</td>
            <td><input type="text" name="map_title" value="<?php echo $map_title; ?>" style="width:190px;" /></td></tr>
        <tr><td>Source</td>
	        <td><input type="text" name="map_source" value="<?php echo $map_source; ?>" id="map_source" onclick="uploadGallery('map_source')" style="width:190px;" /></td>
        </tr>
    </table>
    <?php
}
function tour_custom_box() {
	global $post, $table_prefix, $wpdb;
	$postID		= $post->ID;
	$custom		= get_post_meta( $postID, '_cpt_tour_attr', true );
	$summary	= $custom['_summary'];
	$itinerary	= $custom['_itinerary'];
	$priceInfo	= $custom['_price_info'];
	$dataType	= 1; // 1:Tour <> 2:Hotel
	wp_editor( $summary, 'summary' ); ?>
    <p><table width="100%"><tr><td nowrap="nowrap" width="1%"><strong>Hành trình tour: </strong></td>
    	<td><input type="text" name="itinerary" value="<?php echo $itinerary; ?>" style="width:100%" /></td></tr></table></p>
    <hr class="hrPrice" />
	<p><strong>Tour price includes & excludes: </strong></p>
    <?php wp_editor( $priceInfo, 'price_info' ); 
	$total = $wpdb->get_col("SELECT count(*) AS total FROM {$table_prefix}price_season WHERE post_id=". $post->ID);
	$show_mainGroup = 'none';
	if( $total[0] ) 
		$show_mainGroup = 'inline';
	?>
    <div id="mainPrice" style="padding-top:10px;">
    	<div id="mainGroup" style="display:<?php echo $show_mainGroup; ?>;">
            <table cellspacing="0" cellpadding="4">
                <tr><td><strong>Management groups: </strong></td>
                    <td id="editGroup"><span id="slcContent"><select id="group">
                    <?php
                    $sql_Group = $wpdb->get_results("SELECT * FROM {$table_prefix}price_group WHERE group_type={$dataType} ORDER BY group_name ASC;");
                    $group_arr = array();
                    foreach ( $sql_Group as $sqlGroup ) {
                        echo '<option value="'. $sqlGroup->group_id .'">'. $sqlGroup->group_name .'</option>';
                        $group_arr[$sqlGroup->group_id] = $sqlGroup->group_name;
                    }
                    ?></select></span>
                    <input type="button" value="Insert" class="button" onclick="addGroup(<?php echo $dataType; ?>);" style="font-weight:bold;" />
                    <input type="button" value="Edit" class="button" onclick="editGroup(<?php echo $dataType; ?>);" style="font-weight:bold;" />
                    <input type="button" value="Delete" class="button" onclick="deleteGroup(<?php echo $dataType; ?>);" />
                </td></tr>
            </table>
            <div style="font-style:italic; font-size:11px;"><strong><u>Lưu ý</u>:</strong> Thêm nhóm đầy đủ trước khi tạo bảng giá</div>
            <hr class="hrPrice" />
        </div>
		<?php
        if( $total[0] ) 
        {
            $sql_Season = $wpdb->get_results("SELECT * FROM {$table_prefix}price_season WHERE post_id=". $post->ID ." ORDER BY season_order ASC;");
            foreach ( $sql_Season as $sqlSeason ) 
            {	
                $sql_Class = $wpdb->get_results("SELECT * FROM {$table_prefix}price_class WHERE season_id=". $sqlSeason->season_id ." ORDER BY class_order ASC;");
                $numberClass = count($sql_Class);
                ?>
                <div id="mainSeaDB_<?php echo $sqlSeason->season_id; ?>">
                <table width="100%" cellspacing="1" cellpadding="4" border="1" class="tblSeason">
                    <tr align="center">
                        <th width="37px">Status</th>
                        <th width="33px">Order</th>
                        <th>Season Name</th>
                        <th width="21px">Edit</th>
                        <th width="36px">Delete</th></tr>
                    <tr align="center">
                        <td width="37px"><div id="seaStatus_<?php echo $sqlSeason->season_id; ?>">
                            <a href="javascript:;" onclick="changeStatus('seaStatus_<?php echo $sqlSeason->season_id; ?>', <?php echo $sqlSeason->season_id; ?>, <?php echo $sqlSeason->season_status; ?>, 'price_season');"><img src="<?php echo TEMPLATE_URL; ?>/images/<?php echo (($sqlSeason->season_status) ? 'icon_enable.gif' : 'icon_disable.gif'); ?>" alt="" /></a></div>
                        </td>
                        <td width="33px" class="item order_<?php echo $sqlSeason->season_id; ?>"><?php echo $sqlSeason->season_order; ?></td>
                        <td class="item name_<?php echo $sqlSeason->season_id; ?>"><?php echo $sqlSeason->season_name; ?></td>
                        <td width="21px" class="edit_<?php echo $sqlSeason->season_id; ?>"><a href="javascript:;" onclick="editSeason(<?php echo $sqlSeason->season_id; ?>)"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_edit.gif" alt="" /></a></td>
                        <td width="36px"><a href="javascript:;" onclick="deleteSeason('mainSeaDB_<?php echo $sqlSeason->season_id; ?>', <?php echo $sqlSeason->season_id; ?>);"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_delete.gif" alt="" /></a></td></tr>
                </table>
                <textarea id="info_<?php echo $sqlSeason->season_id; ?>" style="width:100%; height:80px; display:none;"><?php echo $sqlSeason->season_info; ?></textarea>
                <input type="text" id="className_<?php echo $sqlSeason->season_id; ?>" style="width:150px; margin:0;" />
                <input type="button" value="Insert new class" class="button" onclick="addClass(<?php echo $sqlSeason->season_id; ?>, 'new', <?php echo $post->ID; ?>, <?php echo $dataType; ?>)" style="font-weight:bold;" />
                <input type="hidden" id="numClass_<?php echo $sqlSeason->season_id; ?>" value="0" />
                <table width="100%" cellspacing="1" cellpadding="4" border="1" class="tblPrice" id="tblPrice_<?php echo $sqlSeason->season_id; ?>">
                    <tr><th width="37px">Status</th>
                        <th width="33px">Order</th>
                        <th>Class Name</th>
                        <th width="63px" nowrap="nowrap">Extra Price</th>
                        <th width="21px">Edit</th>
                        <th width="36px">Delete</th>
                    </tr>
                <?php 
				foreach( $sql_Class as $sqlClass ) 
				{
					?>
					<tr align="center" class="classDB_<?php echo $sqlClass->class_id; ?>">
						<td width="37px"><div id="classStatus_<?php echo $sqlClass->class_id; ?>">
							<a href="javascript:;" onclick="changeStatus('classStatus_<?php echo $sqlClass->class_id; ?>', <?php echo $sqlClass->class_id; ?>, <?php echo $sqlClass->class_status; ?>, 'price_class');"><img src="<?php echo TEMPLATE_URL; ?>/images/<?php echo (($sqlClass->class_status) ? 'icon_enable.gif' : 'icon_disable.gif'); ?>" alt="" /></a></div>
						</td>
						<td width="33px" class="item clsOrder_<?php echo $sqlClass->class_id; ?>"><?php echo $sqlClass->class_order; ?></td>
						<td nowrap="nowrap" class="item clsName_<?php echo $sqlClass->class_id; ?>"><?php echo $sqlClass->class_name; ?></td>
						<td width="63px" class="item clsExtra_<?php echo $sqlClass->class_id; ?>"><?php echo $sqlClass->class_extra; ?></td>
						<td width="21px" id="clsEdit_<?php echo $sqlClass->class_id; ?>"><a href="javascript:;" onclick="editClass(<?php echo $sqlClass->class_id; ?>, 'clsOrder_<?php echo $sqlClass->class_id; ?>', 'clsName_<?php echo $sqlClass->class_id; ?>', 'clsExtra_<?php echo $sqlClass->class_id; ?>');"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_edit.gif" alt="" /></a></td>
						<td width="36px"><a href="javascript:;" onclick="deleteClass('classDB_<?php echo $sqlClass->class_id; ?>', <?php echo $sqlClass->class_id; ?>);"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_delete.gif" alt="" /></a></td></tr>
					<tr class="classDB_<?php echo $sqlClass->class_id; ?>">
						<td colspan="6">
						<table cellspacing="1" cellpadding="4" border="1" class="tblPrs" id="tblPrs_<?php echo $sqlClass->class_id; ?>" align="center" style="background-color:white;">
							<tr><th width="90px">Nhóm khách</th><th width="90px">Giá hợp đồng</th><th width="90px">Giá trên web</th><th width="21px">Edit</th><th width="36px">Delete</th></tr>
						<?php 
						$sql_Price = $wpdb->get_results("SELECT * FROM {$table_prefix}price WHERE class_id=". $sqlClass->class_id ." ORDER BY price_public DESC;");
						foreach( $sql_Price as $sqlPrice ) {
							echo '<tr class="priceDB_'. $sqlPrice->price_id .'" align=center>
								<td width="90px" class="item prsGroDB_'. $sqlPrice->price_id .'">'. $group_arr[$sqlPrice->group_id] .'</td>
								<td width="90px" class="item prsConDB_'. $sqlPrice->price_id .'">'. $sqlPrice->price_contract .'</td>
								<td width="90px" class="item prsPubDB_'. $sqlPrice->price_id .'">'. $sqlPrice->price_public .'</td>
								<td width="21px" class="prsEdit_'. $sqlPrice->price_id .'"><a href="javascript:;" onclick="editPrice('. $sqlPrice->price_id .', '. $sqlPrice->group_id .', \'prsGroDB_'. $sqlPrice->price_id .'\', \'prsConDB_'. $sqlPrice->price_id .'\', \'prsPubDB_'. $sqlPrice->price_id .'\');"><img src="'. TEMPLATE_URL .'/images/icon_edit.gif" alt="" /></a></td>
								<td width="36px"><a href="javascript:;" onclick="deletePrice(\'priceDB_'. $sqlPrice->price_id .'\', '. $sqlPrice->price_id .');"><img src="'. TEMPLATE_URL .'/images/icon_delete.gif" alt="" /></a></td></tr>';
						}
						?>
						<tr class="price_<?php echo $sqlClass->class_id; ?>_1" align="center"></tr>
						</table>
						<div align="center"><input type="button" value="Insert new price" class="button" onclick="addPrice(<?php echo $sqlClass->class_id; ?>, 'new')" style="font-weight:bold;" /></div>
						<input type="hidden" id="numPrice_<?php echo $sqlClass->class_id; ?>" value="0" /><br /></td>
					</tr>
					<?php
				}
				echo '<tr class="class_'. $sqlSeason->season_id .'_1" align="center"></tr>
				</table>';
                ?><hr class="hrPrice" />
                </div><!--end #mainClass_-->
                <?php
            } // endforeach price_season
            $wpdb->flush();
        } ?>
        <input type="hidden" id="numSeason" value="0" />
        <div id="mainSeason_1"></div>
        <input type="button" value="Tạo bảng giá mới" class="button" onclick="addSeason(<?php echo $post->ID; ?>, 'new', <?php echo $dataType; ?>);" />
    </div>
	<?php
}

/* When the post is saved, saves our custom data */
function myplugin_save_postdata( $post_id ) 
{
	global $wpdb, $table_prefix;
	
	// verify if this is an auto save routine. 
	// If it is our form has not been submitted, so we dont want to do anything
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
		return;
	// Check permissions
	if ( ( isset ( $_POST['post_type'] ) ) && ( 'page' == $_POST['post_type'] )  ) {
		if ( ! current_user_can( 'edit_page', $post_id ) ) {
			return;
		}    
	}
	else {
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}
	}
	
	// verify this came from the our screen and with proper authorization,
	// because save_post can be triggered at other times
	if ( ! wp_verify_nonce( $_POST['cpt_noncename'], plugin_basename( __FILE__ ) ) )
		return;
	
	$new_set_top = $_POST['top_tour'];
	if ( isset($new_set_top) ) {
		update_post_meta($post_id, '_cpt_top_tour', 1);
	} else {
		delete_post_meta($post_id, '_cpt_top_tour');
	}
	
	$duration = $_POST['duration_option'];
	wp_set_object_terms( $post_id, $duration, 'tour_duration' );
	
	$my_postmeta['_trip_code']	= $_POST['trip_code'];
	$my_postmeta['_price_from']	= $_POST['price_from'];
	$my_postmeta['_price_to']	= $_POST['price_to'];
	$my_postmeta['_map_title']	= $_POST['map_title'];
	$my_postmeta['_map_source']	= $_POST['map_source']; 
	$my_postmeta['_summary']	= $_POST['summary']; 
	$my_postmeta['_itinerary']	= $_POST['itinerary']; 
	$my_postmeta['_price_info']	= $_POST['price_info']; 
	update_post_meta($post_id, '_cpt_tour_attr', $my_postmeta);	
	return $post_id;
}

function delete_postdata_when_remove_in_trash( $post_id ) {
	global $wpdb, $table_prefix;
    //$wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE post_id = %d", $post_id));
	//
	$price_season = $wpdb->get_results("SELECT season_id FROM {$table_prefix}price_season WHERE post_id=". $post_id);
	foreach( $price_season as $seasons ) {
		$price_class = $wpdb->get_results("SELECT class_id FROM {$table_prefix}price_class WHERE season_id=". $seasons->season_id);
		foreach ( $price_class as $classes ) {
			$wpdb->query("DELETE FROM {$table_prefix}price WHERE class_id=". $classes->class_id);
		}
		$wpdb->query("DELETE FROM {$table_prefix}price_class WHERE season_id=". $seasons->season_id);
	}
	$wpdb->query("DELETE FROM {$table_prefix}price_season WHERE post_id=". $post_id);
	return true;
}

function add_script_for_meta_box() { ?>
	<script type="text/javascript" src="<?php echo FOLDER_JS; ?>/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
	/*$(document).ready(function() {
		$("select#tagDiv").change(function() {
			if( $(this).val() != 0 ) {
				alert($(this).val());
			$('.attachment-display-settings .alignment').selectOptions("none", true);
			});
		var tagDiv = $("select#tagDiv option").val()
		alert(tagDiv);
	});
	*/
    function sprintf(format, etc) {
        var arg = arguments;
        var i = 1;
        return format.replace(/%((%)|s)/g, function (m) { return m[2] || arg[i++] })
    }
    var loading 	= '<img src="<?php echo FOLDER_IMG; ?>/loading/loading%s.gif" alt="" />';
	var loading15	= '<img src="<?php echo FOLDER_IMG; ?>/loading/loading15.gif" alt="" />';
	var loading11	= '<img src="<?php echo FOLDER_IMG; ?>/loading/loading11.gif" alt="" />';
	var loading2	= '<img src="<?php echo FOLDER_IMG; ?>/loading/loading2.gif" alt="" />';
    //alert(sprintf(loading, 15));
    
    function changeStatus( idDiv, ID, status, tbl, fid, field ) {
        $('#'+idDiv).html(sprintf(loading, 2));
        $.ajax({
            type: "POST",
            url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
            data: 'url=change_Status,'+ idDiv +','+ ID +','+ status +','+ tbl +','+ fid +','+ field,
            cache: false,
            success: function(data){
                $('#'+idDiv).show().fadeIn(100).html(data);
            }
        });
        return false;
    }
    
	function uploadGallery( divID ) 
	{
		var tbframe_interval = setInterval(function() {jQuery('#TB_iframeContent').contents().find('.savesend .button').val('Use This Image');}, 2000);
		formfield = jQuery('#'+ divID).attr('name');
		tb_show('', 'media-upload.php?tab=library&TB_iframe=true');
		window.send_to_editor = function(html) {
			//clear interval for "Use this Button" so button text resets
			clearInterval(tbframe_interval);
			url = $(html).html(html).find('img').attr('src'); //jQuery(html).attr('href');
			jQuery('#'+ divID).val(url);
			tb_remove();
			formfield = '';
		};
		return false;
	}

	function jquery_response_select_tagDiv( sel ) {
		var value = sel.options[sel.selectedIndex].value;  
		if( value != 0 ) 
			$('.attachment-display-settings .alignment option[value="none"]').attr("selected", "selected");
	}
	
	function addGroup( gType ) {
		jQuery('#editGroup').html('<input type="text" id="groupTitle" style="width:150px;" />' + 
			'<input type="button" value="Insert" class="button" onclick="insertGroup('+ gType +', \'groupTitle\');" style="font-weight:bold;" />' + 
			'<input type="button" value="Cancel" class="button" onclick="cancelGroup('+ gType +');" />'
		);
		jQuery('#groupTitle').focus();
		return false;
	}
	function editGroup( gType ) {
		jQuery('#editGroup').html('<input type="text" id="groupTitle" value="'+ jQuery('#group :selected').text() +'" style="width:150px;" />' + 
			'<input type="button" value="Update" class="button" onclick="udpateGroup('+ gType +', '+ jQuery('#group').val() +', \'groupTitle\');" style="font-weight:bold;" />' + 
			'<input type="button" value="Cancel" class="button" onclick="cancelGroup('+ gType +');" />'
		);
		jQuery('#groupTitle').focus();
		return false;
	}
	function cancelGroup( gType ) {
		jQuery('#editGroup').fadeOut().html(loading2);
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=cancel_Group,'+ gType,
			cache: false,
			success: function(data){
				jQuery('#editGroup').show().fadeIn(100).html(data);
			}
		});
		return false;
	}
	function insertGroup( gType, groupTitle ) {
		jQuery('#editGroup').fadeOut(100);
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=insert_Group,'+ gType +','+ document.getElementById(groupTitle).value.replace(/\+/g, "^plus"),
			cache: false,
			success: function(data){
				jQuery('#editGroup').show().fadeIn(100).html(data);
			}
		});
		return false;
	}
	function udpateGroup( gType, groupID, groupTitle ) {
		jQuery('#editGroup').fadeOut(100);
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=update_Group,'+ gType +','+ groupID +','+ document.getElementById(groupTitle).value.replace(/\+/g, "^plus"),
			cache: false,
			success: function(data){
				jQuery('#editGroup').show().fadeIn(100).html(data);
			}
		});
		return false;
	}
	function deleteGroup( gType ) {
		if( confirm('Uầy, có chắc muốn xóa nhóm khách này không ?') )
		{
			jQuery('#editGroup').fadeOut(100);
			jQuery.ajax({
				type: "POST",
				url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
				data: 'url=delete_Group,'+ gType +','+ jQuery('#group').val(),
				cache: false,
				success: function(data){
					jQuery('#editGroup').show().fadeIn(100).html(data);
				}
			});
		}
		return false;
	}
	
	function addSeason( postID, isNew, sType ) {
		var numSea	= jQuery('#numSeason').val();
		// Tăng biến ẩn lên 1 đơn vị
		numSea		= parseInt(numSea) + 1;
		jQuery('#numSeason').val(numSea);
		// Load nội dung html vào tag div
		var htmlNewSeason = '<table width="100%">'+
				'<tr><td width="1%" nowrap="nowrap">Season name:</td><td><input type="text" id="seaName_'+ numSea +'" style="width:100%;" /></td></tr>'+
				'<tr valign="top"><td>Note:</td><td><textarea id="seaText_'+ numSea +'" style="width:100%; height:80px;"></textarea></td></tr>'+
			'</table>'+
			'<div style="padding: 10px 0pt; width: 100%; text-align: center;">'+
				'<input type="button" value="Submit" onclick="insertSeason(\'mainSeason_'+ numSea +'\', '+ numSea +', '+ postID +', \'seaName_'+ numSea +'\', \'seaText_'+ numSea +'\', \''+ isNew +'\', '+ sType +');" class="button" style="font-weight:bold" />'+
				'<input type="button" value="Cancel" onclick="cancelSeason(\'mainSeason_'+ numSea +'\')" class="button" />'+
			'</div>';
		jQuery('#mainSeason_'+ numSea).html(htmlNewSeason).hide().slideDown('slow');
		
		// Thêm div main Season
		jQuery('#mainSeason_'+ numSea).after('<div id="mainSeason_'+ (parseInt(numSea) + 1) +'"></div>');
		return false;
	}
	function cancelSeason( idDiv ) {
		jQuery('#'+ idDiv).slideUp('slow', function(){ jQuery('#'+ idDiv).remove() });
		return false;
	}
	function insertSeason( idDiv, stt, postID, seaName, seaText, isNew, sType ) {
		if( isNew == 'new' ) {
			jQuery('#mainGroup').css('display','inline');
		}
		var seaName = document.getElementById(seaName).value;
		var seaText = document.getElementById(seaText).value;
		jQuery('#'+ idDiv).html(loading11).hide().fadeIn('slow');
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=insert_Season,'+ stt +','+ postID +','+ seaName.replace(/\,/g, "^phay").replace(/&/g, "^va") +','+ seaText.replace(/\,/g, "^phay").replace(/&/g, "^va") +','+ idDiv +','+ sType,
			cache: false,
			success: function(data){
				jQuery('#'+idDiv).html(data).fadeIn('slow');
			}
		});
		return false;
	}
	function editSeason( ID ) {
		jQuery('.order_'+ID).html('<input type="text" value="' + jQuery('.order_'+ ID).text() + '" id="order_'+ ID +'" style="width:30px;" />');
		jQuery('.name_'+ ID).html('<input type="text" value="' + jQuery('.name_'+ ID).text().replace(/"/g, '&quot;') + '" id="name_'+ ID +'" style="width:300px" />');
		jQuery('#info_'+ ID).css('display', 'inline');
		jQuery('.edit_'+ ID).html('<a href="javascript:;" onclick="saveSeason('+ ID +', \'order_'+ ID +'\', \'name_'+ ID +'\', \'info_'+ ID +'\')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_sync.gif" alt="" /></a>');
		jQuery('#name_'+ ID).focus();
		return false;
	}
	function saveSeason( ID, order, name, info ) {
		var order	= document.getElementById(order).value;
		var name	= document.getElementById(name).value;
		var info	= document.getElementById(info).value;
		var words	= /(,)|(&)/g;
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=save_Season,'+ ID +','+ order +','+ name.replace(/\,/g, "^phay").replace(/&/g, "^va") +','+ info.replace(/\,/g, "^phay").replace(/&/g, "^va"),
			cache: false,
			success: function(data){
				jQuery('.order_'+ID).html(order);
				jQuery('.name_'+ ID).html(name);
				jQuery('#info_'+ ID).css('display', 'none');
				jQuery('.edit_'+ ID).html('<a href="javascript:;" onclick="editSeason('+ ID +')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_edit.gif" alt="" /></a>');
			}
		});
		return false;
	}
	function deleteSeason( idDiv, ID ) {
		if( confirm('Uầy, có chắc muốn xóa dữ liệu này không ?') )
		{
			jQuery.ajax({
				type: "POST",
				url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
				data: 'url=delete_Season,'+ ID,
				cache: false,
				success: function(data){
					jQuery('#'+ idDiv).slideUp('slow', function(){ jQuery('#'+ idDiv).remove() });
				}
			});
		}
		return false;
	}
	
	function addClass( seasonID, isNew, postID, cType ) {
		var numCls	= jQuery('#numClass_'+ seasonID).val();
		// Tăng biến ẩn lên 1 đơn vị
		numCls		= parseInt(numCls) + 1;
		jQuery('#numClass_'+ seasonID).val(numCls);
		// Load nội dung html vào tag div .replace(/"/g, '&quot;')   replace(/\,/g, "^phay").replace(/&/g, "^va")
		var htmlNewClass = '<td width="37px"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_enable.gif" alt="" /></td>'+
			'<td width="33px"><input type="text" value="" id="clsOrder_'+ seasonID +'_'+ numCls +'" style="width:30px;" /></td>'+
			'<td><input type="text" value="'+ document.getElementById('className_'+ seasonID).value.replace(/"/g, '&quot;') +'" id="clsName_'+ seasonID +'_'+ numCls +'" style="width:300px;" /></td>'+
			'<td width="63px"><input type="text" value="" id="clsExtra_'+ seasonID +'_'+ numCls +'" style="width:60px;" /></td>'+
			'<td width="21px"><a href="javascript:;" onclick="saveClass('+ seasonID +', \'clsOrder_'+ seasonID +'_'+ numCls +'\', \'clsName_'+ seasonID +'_'+ numCls +'\', \'clsExtra_'+ seasonID +'_'+ numCls +'\', \'new\', '+ postID +', \'class_'+ seasonID +'_'+ numCls +'\', '+ cType +')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_sync.gif" alt="" /></a></td>'+
			'<td width="36px"><a href="javascript:;" onclick="deleteClass(\'class_'+ seasonID +'_'+ numCls +'\', 0);"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_delete.gif" alt="" /></a></td></tr>';
		jQuery('tr.class_'+ seasonID +'_'+ numCls).html(htmlNewClass).hide().fadeIn('slow');
		// Thêm tag tr > class
		jQuery('table#tblPrice_'+ seasonID).after().append('<tr class="class_'+ seasonID +'_'+ (parseInt(numCls) + 1) +'" align="center"></tr>');
		return false;
	}
	function editClass( ID, clsOrder, clsName, clsExtra ) {
		jQuery('.'+ clsOrder).html('<input type="text" value="' + jQuery('.'+ clsOrder).text() + '" id="'+ clsOrder +'" style="width:30px;" />');
		jQuery('.'+ clsName).html('<input type="text" value="' + jQuery('.'+ clsName).text().replace(/"/g, '&quot;') + '" id="'+ clsName +'" style="width:300px" />');
		jQuery('.'+ clsExtra).html('<input type="text" value="' + jQuery('.'+ clsExtra).text() + '" id="'+ clsExtra +'" style="width:60px" />');
		jQuery('#clsEdit_'+ ID).html('<a href="javascript:;" onclick="saveClass('+ ID +', \''+ clsOrder +'\', \''+ clsName +'\', \''+ clsExtra +'\')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_sync.gif" alt="" /></a>');
		return false;
	}
	function saveClass( ID, orderID, nameID, extraID, isNew, postID, trClass, cType ) {
		var strOrder= document.getElementById(orderID).value;
		var strName	= document.getElementById(nameID).value;
		var strExtra= document.getElementById(extraID).value;
	
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=save_Class,'+ ID +','+ strOrder +','+ strName.replace(/\,/g, "^phay").replace(/&/g, "^va") +','+ strExtra +','+ isNew +','+ postID +','+ trClass +','+ cType,
			cache: false,
			success: function(data){
				if( isNew == 'new' ) {
					var htmlNewClass = '<td width="37px"><div id="classStatus_'+ data +'">'+
							'<a href="javascript:;" onclick="changeStatus(\'classStatus_'+ data +'\', '+ data +', 1, \'price_class\');"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_enable.gif" alt="" /></a></div></td>'+
						'<td width="33px" class="item clsOrder_'+ data +'">'+ strOrder +'</td>'+
						'<td nowrap="nowrap" class="item clsName_'+ data +'">'+ strName +'</td>'+
						'<td width="63px" class="item clsExtra_'+ data +'">'+ strExtra +'</td>'+
						'<td width="21px" id="clsEdit_'+ data +'"><a href="javascript:;" onclick="editClass('+ data +', \'clsOrder_'+ data +'\', \'clsName_'+ data +'\', \'clsExtra_'+ data +'\');"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_edit.gif" alt="" /></a></td>'+
						'<td width="36px"><a href="javascript:;" onclick="deleteClass(\'classDB_'+ data +'\', '+ data +');"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_delete.gif" alt="" /></a></td>';
					jQuery('tr.'+ trClass).removeClass(trClass).addClass('classDB_'+ data);
					jQuery('tr.classDB_'+ data).html(htmlNewClass);
					
					var htmlNewPrice = '<table cellspacing="1" cellpadding="4" border="1" class="tblPrs" id="tblPrs_'+ data +'" align="center" style="background-color:white;">'+
						'<tr><th width="90px">Nhóm khách</th><th width="90px">Giá hợp đồng</th><th width="90px">Giá trên web</th><th width="21px">Edit</th><th width="36px">Delete</th></tr>'+
						'<tr class="price_'+ data +'_1" align="center"></tr></table>'+
						'<div align="center"><input type="button" value="Insert new price" class="button" onclick="addPrice('+ data +', \'new\')" style="font-weight:bold;" /></div>'+
						'<input type="hidden" id="numPrice_'+ data +'" value="0" /><br />';
					jQuery('tr.classDB_'+ data).after('<tr class="classDB_'+ data +'"><td colspan="6">'+ htmlNewPrice +'</td></tr>');
				} else {
					jQuery('.'+ orderID).html(strOrder);
					jQuery('.'+ nameID).html(strName);
					jQuery('.'+ extraID).html(strExtra);
					jQuery('#clsEdit_'+ ID).html('<a href="javascript:;" onclick="editClass('+ ID +', \''+ orderID +'\', \''+ nameID +'\', \''+ extraID +'\')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_edit.gif" alt="" /></a>');
				}
			}
		});
		return false;
	}
	function deleteClass( idDiv, ID ) {
		if( ID ) 
		{
			if( confirm('Oạch, có chắc muốn xóa dữ liệu này không ?') ) {
				jQuery.ajax({
					type: "POST",
					url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
					data: 'url=delete_Class,'+ ID,
					cache: false,
					success: function(data){
						jQuery('.'+ idDiv).remove();
					}
				});
			}
		} else 
			jQuery('.'+ idDiv).remove();
		return false;
	}
	
	function addPrice( classID, isNew ) {
		var numPri	= jQuery('#numPrice_'+ classID).val();
		// Tăng biến ẩn lên 1 đơn vị
		numPri		= parseInt(numPri) + 1;
		jQuery('#numPrice_'+ classID).val(numPri);
		var slcContent = jQuery('#slcContent').html();
		slcContent = slcContent.replace('id="group"', 'id="prsGro_'+ classID +'_'+ numPri +'"');
		// Load nội dung html vào tag div
		var htmlNewPrice = '<td width="90px" class="item prsGro_'+ classID +'_'+ numPri +'">'+ slcContent +'</td>'+
			'<td width="90px" class="item prsCon_'+ classID +'_'+ numPri +'"><input type="text" value="" id="prsCon_'+ classID +'_'+ numPri +'" style="width:78px;" /></td>'+
			'<td width="90px" class="item prsPub_'+ classID +'_'+ numPri +'"><input type="text" value="" id="prsPub_'+ classID +'_'+ numPri +'" style="width:78px;" /></td>'+
			'<td width="21px" class="prsEdit_'+ classID +'_'+ numPri +'"><a href="javascript:;" onclick="savePrice('+ classID +', \'prsGro_'+ classID +'_'+ numPri +'\', \'prsCon_'+ classID +'_'+ numPri +'\', \'prsPub_'+ classID +'_'+ numPri +'\', \'new\', \'prsEdit_'+ classID +'_'+ numPri +'\', \''+ classID +'_'+ numPri +'\')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_sync.gif" alt="" /></a></td>'+
			'<td width="36px" class="'+ classID +'_'+ numPri +'"><a href="javascript:;" onclick="deletePrice(\'price_'+ classID +'_'+ numPri +'\', 0);"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_delete.gif" alt="" /></a></td></tr>';
		jQuery('tr.price_'+ classID +'_'+ numPri).show().html(htmlNewPrice);
		// Thêm tag tr > price
		jQuery('table#tblPrs_'+ classID).after().append('<tr class="price_'+ classID +'_'+ (parseInt(numPri) + 1) +'" align="center"></tr>');
		return false;
	}
	function editPrice( ID, GroupID, groID, conID, pubID ) {
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=load_GroupPrice,'+ GroupID +','+ groID,
			cache: false,
			success: function(data){
				jQuery('.'+ groID).html(data);
			}
		});
		jQuery('.'+ conID).html('<input type="text" value="' + jQuery('.'+ conID).text() + '" id="'+ conID +'" style="width:78px;" />');
		jQuery('.'+ pubID).html('<input type="text" value="' + jQuery('.'+ pubID).text() + '" id="'+ pubID +'" style="width:78px;" />');
		jQuery('.prsEdit_'+ ID).html('<a href="javascript:;" onclick="savePrice('+ ID +', \''+ groID +'\', \''+ conID +'\', \''+ pubID +'\')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_sync.gif" alt="" /></a>');
		return false;
	}
	function savePrice( ID, groID, conID, pubID, isNew, divEdit, divDel ) {
		var strGro	= document.getElementById(groID);
		var strCon	= document.getElementById(conID).value;
		var strPub	= document.getElementById(pubID).value;
		jQuery.ajax({
			type: "POST",
			url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
			data: 'url=save_Price,'+ ID +','+ strGro.value +','+ strCon +','+ strPub +','+ isNew,
			cache: false,
			success: function(data){
				jQuery('.'+ groID).html(strGro.options[strGro.selectedIndex].text);
				jQuery('.'+ conID).html(strCon);
				jQuery('.'+ pubID).html(strPub);
				if( isNew == 'new' ) {
					jQuery('.'+ divEdit).removeClass(divEdit).addClass('prsEdit_'+ data);
					jQuery('.'+ divDel).html('<a href="javascript:;" onclick="deletePrice(\'price_'+ divDel +'\', '+ data +');"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_delete.gif" alt="" /></a>');
				}
				jQuery('.prsEdit_'+ data).html('<a href="javascript:;" onclick="editPrice('+ data +', '+ strGro.value +', \''+ groID +'\', \''+ conID +'\', \''+ pubID +'\')"><img src="<?php echo TEMPLATE_URL; ?>/images/icon_edit.gif" alt="" /></a>');
			}
		});
		return false;
	}
	function deletePrice( idDiv, ID ) {
		if( ID ) {
			jQuery.ajax({
				type: "POST",
				url: "<?php echo TEMPLATE_URL; ?>/libs/actions.php",
				data: 'url=delete_Price,'+ ID,
				cache: false,
				success: function(data){
					jQuery('.'+ idDiv).remove();
				}
			});
		} else 
			jQuery('.'+ idDiv).remove();
		return false;
	}
    </script>
    <?php 
} 

function add_css_for_meta_box() { ?>
	<style type="text/css">
	#mainPrice th, #mainPrice td {
		padding: 5px;
	}
	#mainPrice th {
		background-color: #12A3EB;
		color: white;
	}
	#mainPrice tr:hover {
		background-color: #EBEBEB;
	}
	#mainPrice td.item {
		font-weight: bold;
	}
	td.seaInfo {
		display: none;
	}
	.tblSeason, .tblSeason th, .tblSeason td {
		border: 1px solid #6BC3EF;
	}
	.tblSeason, .tblSeason th, .tblSeason td, .tblPrice, .tblPrice th, .tblPrice td, .tblPrs, .tblPrs th, .tblPrs td {
		border-collapse: collapse;
	}
	.tblPrice, .tblPrice th, .tblPrice td {
		border: 1px solid #DDD;
	}
	.tblPrs, .tblPrs th, .tblPrs td {
		border: 1px solid #F5F5F5;
	}
	#mainPrice table.tblPrice th.pax {
		background-color: #656565;
	}
	#mainPrice table.tblPrice th, #mainPrice table.tblPrs th {
		background-color: #3E3E3E;
		color: white;
	}
	.hrPrice {
		border: 3px double #D9D9D9;
		margin-top: 20px;
	}
	.form-field input.ed_button{
		width: auto;
	}
	#postInfo .wp-editor-container, #tourInfo .wp-editor-container, #post_hotelInfo .wp-editor-container {
		background-color: white;
	} 
    </style><?php
}

function my_meta_clean(&$arr)
{
	if (is_array($arr)) {
		foreach ($arr as $i => $v) {
			if (is_array($arr[$i])) {
				my_meta_clean($arr[$i]);
				if (!count($arr[$i]))
					unset($arr[$i]);
			} else {
				if (trim($arr[$i]) == '')
					unset($arr[$i]);
			}
		}
		if (!count($arr))
			$arr = NULL;
	}
}

?>